package com.hanxiaozhang.basicknowledgecode.charset;

import java.io.UnsupportedEncodingException;

/**
 * 〈一句话功能简述〉<br>
 * 〈字符集转换〉
 *
 * @author hanxinghua
 * @create 2023/5/6
 * @since 1.0.0
 */
public class No2CharsetConvert {


    public static void main(String[] args) throws UnsupportedEncodingException {

        String str = "杩欐槸鍦ㄤ富鏈哄悕瑙ｆ瀽鏃堕�氬父鍑虹幇鐨勬殏鏃堕敊璇紝瀹冩剰鍛崇潃鏈湴鏈嶅姟鍣ㄦ病鏈変粠鏉冨▉鏈嶅姟鍣ㄤ笂鏀跺埌鍝嶅簲銆�";

        System.out.println(getCharset(str));

        // 字符集转换
        String s2 = new String(str.getBytes("GBK"), "UTF-8");
        System.out.println(s2);

        System.out.println(getUTF8StringFromGBKString(str));

    }


    /**
     * https://www.cnblogs.com/kn-zheng/p/17025035.html
     * 不太对
     *
     * @param gbkStr
     * @return
     */
    public static String getUTF8StringFromGBKString(String gbkStr) {
        try {
            return new String(getUTF8BytesFromGBKString(gbkStr), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new InternalError();
        }
    }

    public static byte[] getUTF8BytesFromGBKString(String gbkStr) {
        int n = gbkStr.length();
        byte[] utfBytes = new byte[3 * n];
        int k = 0;
        for (int i = 0; i < n; i++) {
            int m = gbkStr.charAt(i);
            if (m < 128 && m >= 0) {
                utfBytes[k++] = (byte) m;
                continue;
            }
            utfBytes[k++] = (byte) (0xe0 | (m >> 12));
            utfBytes[k++] = (byte) (0x80 | ((m >> 6) & 0x3f));
            utfBytes[k++] = (byte) (0x80 | (m & 0x3f));
        }
        if (k < utfBytes.length) {
            byte[] tmp = new byte[k];
            System.arraycopy(utfBytes, 0, tmp, 0, k);
            return tmp;
        }
        return utfBytes;
    }


    /**
     * 获取字符集
     * <p>
     * 我感觉不太对 str 识别是错误的
     *
     * @param str
     * @return
     */
    public static String getCharset(String str) {
        String[] encode = new String[]{"UTF-8", "ISO-8859-1", "GB2312", "GBK", "GB18030", "Big5", "Unicode", "ASCII"};
        for (int i = 0; i < encode.length; i++) {
            try {
                if (str.equals(new String(str.getBytes(encode[i]), encode[i]))) {
                    return encode[i];
                }
            } catch (Exception ex) {
            }
        }
        return "";
    }

}
